<template>
  <div class="course-list">
    <el-card>
      <template #header>
        <div class="header">
          <span>课程管理</span>
          <el-button type="primary" v-if="userType == 9" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            添加课程
          </el-button>
        </div>
      </template>
      
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="标题">
          <el-input v-model="searchForm.title" placeholder="请输入课程标题"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-table :data="courses" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="cover" label="封面" width="100">
          <template #default="scope">
            <el-image v-if="scope.row.cover" :src="getIconUrl(scope.row.cover)" style="width: 60px; height: 60px;" :preview-src-list="[getIconUrl(scope.row.cover)]" />
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="课程标题" />
        <el-table-column prop="desc" label="课程描述" :show-overflow-tooltip="true">
          <template #default="scope">
            {{ scope.row.desc && scope.row.desc.length > 50 ? scope.row.desc.substring(0, 50) + '...' : scope.row.desc }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格（元）" width="120">
          <template #default="scope">
            ¥{{ (scope.row.price / 100).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="book_num" label="预订数" width="100" />
        <el-table-column prop="creator.name" label="创建者" width="100" />
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" text @click="handleViewDetail(scope.row)">查看详情</el-button>
            <el-button type="primary" v-if="userType == 9" text @click="handleEdit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 共用对话框：用于新增和编辑 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加课程' : '编辑课程'"
      width="600px"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="课程标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入课程标题"/>
        </el-form-item>
        <el-form-item label="课程描述" prop="desc">
          <el-input v-model="formData.desc" placeholder="请输入课程描述" type="textarea" rows="4"/>
        </el-form-item>
        <el-form-item label="价格（分）" prop="price">
          <el-input-number v-model="formData.price" :min="0" :step="100" placeholder="请输入价格（单位：分）"/>
        </el-form-item>
        <el-form-item label="预订数" prop="book_num">
          <el-input-number v-model="formData.book_num" :min="0" placeholder="请输入预订数"/>
        </el-form-item>
        <el-form-item label="封面图">
          <el-upload
            v-model:file-list="coverList"
            class="upload-demo"
            :auto-upload="false"
            :limit="1"
            accept=".jpg,.jpeg,.png,.webp"
            :on-change="handleCoverChange"
          >
            <el-button type="primary">点击选择封面</el-button>
          </el-upload>
          <el-image v-if="currentCoverUrl" :src="currentCoverUrl" style="width: 120px; height: 120px; margin-top: 10px;" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">{{ submitting ? (dialogType === 'add' ? '上传中...' : '保存中...') : '确定' }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  <div>
    <!-- 整个页面的加载状态 -->
    <div v-loading="loading" class="loading-container" element-loading-text="加载中...">
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useUserStore } from '../../store/user'
import { STATIC_RESOURCE_URL } from '../../config'
import api from '../../api'

export default {
  name: 'CourseList',
  components: {
    Plus
  },
  setup() {
    const router = useRouter()
    const courses = ref([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const loading = ref(false)
    const submitting = ref(false)
    const userStore = useUserStore()
    
    // 搜索表单
    const searchForm = reactive({
      title: ''
    })
    
    // 对话框状态
    const dialogVisible = ref(false)
    const userType = ref(0)
    const dialogType = ref('add')
    const formRef = ref(null)
    const coverList = ref([])
    
    // 表单数据
    const formData = reactive({
      id: '',
      title: '',
      desc: '',
      price: 0,
      book_num: 0,
      cover: ''
    })
    
    // 当前封面URL
    const currentCoverUrl = computed(() => {
      if (coverList.value.length > 0) {
        return URL.createObjectURL(coverList.value[0].raw)
      }
      if (formData.cover) {
        return getIconUrl(formData.cover)
      }
      return ''
    })
    
    // 表单验证规则
    const formRules = {
      title: [
        { required: true, message: '请输入课程标题', trigger: 'blur' }
      ],
      desc: [
        { required: true, message: '请输入课程描述', trigger: 'blur' }
      ],
      price: [
        { required: true, message: '请输入价格', trigger: 'blur' }
      ]
    }
    
    // 获取图标URL
    const getIconUrl = (iconPath) => {
      return `${STATIC_RESOURCE_URL}${iconPath}`
    }
    
    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return ''
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    }
    
    // 加载课程列表
    const loadCourses = async () => {
      loading.value = true
      userType.value = userStore.user?.category
      try {
        const params = {
          skip: (currentPage.value - 1) * pageSize.value,
          limit: pageSize.value
        }
        
        // 添加搜索条件
        if (searchForm.title) {
          params.title = searchForm.title
        }
        
        const response = await api.get('/chance/courses', {
          params
        })
        courses.value = response
        total.value = response.length + (currentPage.value - 1) * pageSize.value
      } catch (error) {
        ElMessage.error('获取课程列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 查询
    const handleSearch = () => {
      currentPage.value = 1
      loadCourses()
    }
    
    // 重置搜索
    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      currentPage.value = 1
      loadCourses()
    }
    
    // 添加课程
    const handleAdd = () => {
      dialogType.value = 'add'
      // 重置表单
      if (formRef.value) {
        formRef.value.resetFields()
      }
      // 初始化表单数据
      formData.id = ''
      formData.title = ''
      formData.desc = ''
      formData.price = 0
      formData.book_num = 0
      formData.cover = ''
      coverList.value = []
      dialogVisible.value = true
    }
    
    // 查看详情
    const handleViewDetail = (row) => {
      router.push(`/courses/${row.id}`)
    }
    
    // 编辑课程
    const handleEdit = (row) => {
      dialogType.value = 'edit'
      // 填充表单数据
      formData.id = row.id
      formData.title = row.title
      formData.desc = row.desc
      formData.price = row.price
      formData.book_num = row.book_num
      formData.cover = row.cover || ''
      coverList.value = []
      dialogVisible.value = true
    }
    
    // 处理封面选择变化
    const handleCoverChange = (file) => {
      // 处理封面文件变化
    }
    
    // 取消操作
    const handleCancel = () => {
      dialogVisible.value = false
      // 清理表单数据
      if (formRef.value) {
        formRef.value.resetFields()
      }
      coverList.value = []
    }
    
    // 提交表单
    const handleSubmit = async () => {
      try {
        submitting.value = true
        await formRef.value.validate(async (valid) => {
          if (valid) {
            try {
              if (dialogType.value === 'add') {
                // 添加模式
                const formDataToSend = new FormData()
                formDataToSend.append('title', formData.title)
                formDataToSend.append('desc', formData.desc)
                formDataToSend.append('price', formData.price)
                formDataToSend.append('book_num', formData.book_num)
                
                // 添加封面（如果有）
                if (coverList.value.length > 0) {
                  formDataToSend.append('cover', coverList.value[0].raw)
                }
                
                await api.post('/chance/courses/', formDataToSend)
                ElMessage.success('课程添加成功')
              } else {
                // 编辑模式
                const formDataToSend = new FormData()
                formDataToSend.append('title', formData.title)
                formDataToSend.append('desc', formData.desc)
                formDataToSend.append('price', formData.price)
                formDataToSend.append('book_num', formData.book_num)
                
                // 添加封面（如果有新选择）
                if (coverList.value.length > 0) {
                  formDataToSend.append('cover', coverList.value[0].raw)
                }
                
                await api.put(`/chance/courses/${formData.id}`, formDataToSend)
                ElMessage.success('课程编辑成功')
              }
              
              handleCancel()
              loadCourses()
            } catch (error) {
              ElMessage.error(dialogType.value === 'add' ? '课程添加失败' : '课程编辑失败')
            }
          }
        })
      } finally {
        submitting.value = false
      }
    }
    
    // 分页处理
    const handleSizeChange = (size) => {
      pageSize.value = size
      loadCourses()
    }
    
    const handleCurrentChange = (current) => {
      currentPage.value = current
      loadCourses()
    }
    
    // 初始加载
    onMounted(() => {
      loadCourses()
    })
    
    return {
      courses,
      total,
      currentPage,
      pageSize,
      loading,
      submitting,
      searchForm,
      dialogVisible,
      userType,
      dialogType,
      formRef,
      coverList,
      formData,
      formRules,
      currentCoverUrl,
      getIconUrl,
      formatDateTime,
      handleSearch,
      resetSearch,
      handleAdd,
      handleViewDetail,
      handleEdit,
      handleCoverChange,
      handleCancel,
      handleSubmit,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.course-list {
  padding: 0;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.upload-demo {
  display: inline-block;
}

.loading-container {
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f9fafb;
  min-height: 200px;
}
</style>
